package com.young.weixin.util;

import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.young.common.util.CollectionUtil;
import com.young.weixin.model.WxMessageRequest;
import com.young.weixin.model.message.WxMessageMapWrapper;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工具类
 *
 * @author wangjiyu
 * @date 2021/10/5 15:25
 */
public class WxUtil {

    /**
     * xml参数转
     *
     * @param wxMessageRequest
     * @param xml
     * @param token
     * @param aesKey
     * @param appid
     * @return
     * @throws Exception
     */
    public static WxMessageMapWrapper checkAndConvertXmlParam(WxMessageRequest wxMessageRequest, String xml, String token, String aesKey, String appid) throws Exception {
        WXBizMsgCrypt pc = new WXBizMsgCrypt(token, aesKey, appid);
        String result2 = pc.decryptMsg(wxMessageRequest.getMsg_signature(), wxMessageRequest.getTimestamp(), wxMessageRequest.getNonce(), xml);
        return new WxMessageMapWrapper(xmlStrToMap(result2));
    }

    /**
     * xml字符串转map
     *
     * @param xmlStr
     * @return
     * @throws Exception
     */
    private static Map<String, String> xmlStrToMap(String xmlStr) throws Exception {
        //返回值
        Map<String, String> resMap = new HashMap<String, String>();
        //将xml字符串解析为xml文档对象
        Document document = DocumentHelper.parseText(xmlStr);
        //获取xml文档对象的根节点元素
        Element root = document.getRootElement();
        //获取根节点下的所有子节点
        List<Element> list = root.elements();
        if (CollectionUtil.isNotEmpty(list)) {
            //迭代节点信息
            for (Element e : list) {
                //得到文本
                String value = e.getText();
                //得到节点名
                String key = e.getName();
                resMap.put(key, value);
            }
        }

        return resMap;
    }

    /**
     * 读取body体数据
     *
     * @param is
     * @return
     * @throws IOException
     */
    public static String readBody(InputStream is) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = is.read(bytes)) > -1) {
            byteArrayOutputStream.write(bytes, 0, len);
        }
        byte[] body = byteArrayOutputStream.toByteArray();
        return new String(body, "UTF-8");
    }

    /**
     * 构建校验参数
     *
     * @param params
     * @return
     */
    public static String buildParamSortStr(String... params) {
        // 字典排序
        Arrays.sort(params);
        StringBuilder sb = new StringBuilder();
        for (String str : params) {
            sb.append(str);
        }
        return sb.toString();
    }
}
